﻿@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "中药处方";
    Layout = null;
    //药品检索，药品是否关联药房库存
    var isMedicineSearchRelatedKC = (ViewBag.ISMedicineSearchRelatedKC as bool?) ?? false;
}
<style type="text/css">
    .newZycfDisableBackgroud {
        background-color: #CCC !important;
    }

    #gridzycf input {
        padding: 6px 0;
    }

    #gridzycf select[role=select] {
        padding: 6px 0;
    }

    #gridzycf input[role=textbox] {
        text-align: center;
    }
</style>
<div id="linkzycf" role="tabpanel" class="tab-pane" style="width:96.5%; float:right; margin-right: 10px; border:solid 1px #ddd; margin-top: 3px;">
    <div class="contentPanel">
        <div style="background-color: #fff;">
            <table id="gridzycf"></table>
            <div id="gridzycfPager"></div>
        </div>
    </div>
    <div id="bottom" style="border-top: solid 1px #ddd; height: 80px; margin-bottom:1px;">
        <form id="formTCM" style="float:left; width:50%; position: relative; top: 25%;">
            <table class="form" id="tableTCMPresAmount">
                <tr>
                    <th class="formTitle"><span class="required">*</span>剂数：</th>
                    <td class="formValue">
                        <input type="text" id="tieshu" name="tieshu" class="form-control required" />
                    </td>
                    <th class="formTitle">处方用法：</th>
                    <td class="formValue">
                        <select id="cfyf" name="cfyf" class="form-control"></select>
                    </td>
                    <td colspan="2">
                        <div class="ckbox" style="margin-left:38px;">
                            <input id="djbz" name="djbz" type="checkbox"><label for="djbz">是否代煎</label>
                        </div>
                    </td>
                </tr>
            </table>
        </form>
        <div class="lowerrightcorner" style="margin-left: 50%; width: 50%; border-left: solid 1px #ddd; height: 100%;">
            <table class="form" style="position: relative; top: 25%;">
                <tr>
                    <th class="formTitle">总金额：</th>
                    <td class="formValue" id="tdTCMTotalAmount"></td>
                    <td style="width: 90px;"></td>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="返回病历" style="margin-left:48%;display:table-cell;" onclick="SaveTCMPres()" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="另存为模板" style="display:table-cell;" onclick="saveAsTCMTemplate()" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-primary" value="F3：保存处方" style="display:table-cell;" onclick="SaveTCMPres('1')" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
</div>

<script>
    var isMedicineSearchRelatedKC = '@(isMedicineSearchRelatedKC)';
    var zycfflag = 0;
    var zylocaldata = new Array();

    function init_TCMPrescription() {
        $.najax({
            url: "/SystemManage/SysBaseData/GetDjFee",
            dataType: "text",
            async: false,
            success: function (data) {
                $('#djbz').attr('data-djfdj',data);
            }
        });

        //仅尚未保存到数据库的处方需要初始化在grid中
        if (window.alldataArray.zycf) {
            zylocaldata = $.jsonWhere($.deepClone.clone(window.alldataArray.zycf), function(icf){
                return !!!icf.cfId;
            });
            $.each(zylocaldata, function () {
                if(!this.cfh){
                    alert('处方异常');
                    location.href = location.href;
                }
                this.action = getTCMActionStr();
            });
        }
        else{
            window.alldataArray.zycf = new Array(); //方便后面使用$.each()
        }

        if (zycfflag === 0) {   //该页面初始化
            gridzycf();
            zycfflag = 1;
            //加载药品用法
            $("#cfyf").bindSelect({
                url: "/SystemManage/SysBaseData/GetZYMedicineUsageList",
                id: "yfCode",
                text: "yfmc"
            });
            var jianfuCode = null;
            $.each($("#cfyf option"), function(){
                if($(this).text() == '煎服'){
                    jianfuCode = $(this).attr('value');
                }
            });
            if(!!jianfuCode){
                $("#cfyf").val(jianfuCode).trigger('change');
            }
            $('#tieshu').val('1');
        }
        else {
            //再次打开该页面
            $("#gridzycf").jqGrid('setGridParam', {
                datatype: 'local',
                data: zylocaldata
            }).trigger("reloadGrid");
            if(zylocaldata && zylocaldata[0] && zylocaldata[0].cfyf){
                $("#cfyf").val(zylocaldata[0].cfyf).trigger('change');
                $("#tieshu").val(zylocaldata[0].tieshu);
                if(!!zylocaldata[0].djbz){
                    $("#djbz").prop('checked', true);
                }
            }

            //
            $('.glyphicon-new-window:visible').parent('div.ui-pg-div').removeClass('newZycfDisableBackgroud');
        }

        //立刻触发编辑其中一个本次就诊的已提交处方（未提交到库中的肯定会在编辑列表中）
        var triggereditcfh = sessionStorage.getItem("triggereditcfh");
        if(!!triggereditcfh){
            sessionStorage.removeItem("triggereditcfh");
            $("#floatLeftMostPartDiv div[data-href='lscf']").trigger('click');
            //未提交到数据库的处方，这里length 0 也没问题
            $('span.bbit-tree-node-text[data-value="' + triggereditcfh + '"]').trigger('click');
        }
    }

    //处方列表
    function gridzycf() {
        var $gridzycf = $("#gridzycf");
        $gridzycf.jqGrid({
            datatype: 'local',
            data: zylocaldata,
            height: $(window).height() - 230,
            //altRows: true,//隔行换色
            shrinkToFit: true,   //true:按比例初始化列宽度 false:使用colModel指定的宽度
            autowidth: true,
            rownumbers: true,  //是否显示序号
            multiselect: true,
            multiboxonly: false,  //复选框 true:不能多选
            editurl: "clientArray",  //行编辑不向服务器提交数据
            unwritten: false,
            colModel: [
                { label: 'cfId', name: 'cfId', hidden: true },
                { label: 'ybwym', name: 'ybwym', hidden: true },
                { label: 'xzsybz', name: 'xzsybz', hidden: true },
                { label: 'cfmxId', name: 'cfmxId', hidden: true },
                { label: 'zxks', name: 'zxks', editable: true, hidden: true },
                { label: 'cfh', name: 'cfh', width: 120, align: 'center', hidden: true },
                { label: 'ypCode', name: 'ypCode', width: 100, editwidth: '100%', align: 'center', editable: true, hidden: true },
                { label: '<span class="required">*</span>名称', name: 'ypmc', width: 285, editwidth: '100%', align: 'center', editable: true },
                { label: '<span class="required">*</span>规格', name: 'ypgg', width: 80, editwidth: '100%', align: 'center', editable: true },
                {label: '<span class="required">*</span>单价', name: 'dj', width: 60, editwidth: '100%', align: 'center', editable: true},
                {
                    label: '<span class="required">*</span>剂量', name: 'mcjl', width: 55, editwidth: '100%', align: 'center', editable: true, editoptions: {
                        dataEvents: [
                                {
                                    type: 'change',
                                    fn: function (e) {
                                        var cellval = $(this).val();
                                        if(cellval.replace(/(^\s*)|(\s*$)/g, "") == ""){
                                            $.modalAlert("剂量为空，请确认。", 'warning');
                                            return;
                                        }
                                        if(isNaN(cellval)){
                                            $.modalAlert("剂量：请填写数字", 'warning');
                                            $(this).val('')
                                            return;
                                        }
                                        var row = $(e.target).closest('tr.jqgrow');
                                        var rowid = row.attr('id');

                                        CalculateTCMEachLineSlANDJe(rowid);
                                    }
                                }
                        ]
                    }
                },
                {
                    label: '<span class="required">*</span>单位', name: 'mcjldw', width: 65, editwidth: '100%', align: 'center', editable: true
                },
                { label: '天数', name: 'ts', width: 60, editwidth: '100%', align: 'center', editable: true, editoptions: {
                    dataEvents: [
                            {
                                type: 'change',
                                fn: function (e) {
                                    var cellval = $(this).val();
                                    if(isNaN(cellval)){
                                        $.modalAlert("剂量：请填写数字", 'warning');
                                        $(this).val('')
                                        return;
                                    }
                                }
                            }
                    ]
                }},
                {
                    label: '<span class="required">*</span>数量', name: 'sl', width: 48, editwidth: '100%', align: 'center', editable: true, editoptions: {
                        dataEvents: [
                            {
                                type: 'change',
                                fn: function (e) {
                                    var cellval = $(this).val();
                                    if (cellval.replace(/(^\s*)|(\s*$)/g, "") == "") {
                                        $.modalAlert("数量为空，请确认。", 'warning');
                                        return;
                                    }
                                    if (isNaN(cellval)) {
                                        $.modalAlert("数量：请填写数字", 'warning');
                                        $(this).val('');
                                        return;
                                    }
                                    var row = $(e.target).closest('tr.jqgrow');
                                    var rowid = row.attr('id');
                                    CalculateTCMEachLineJe(rowid);   //计算明细金额和处方金额
                                }
                            }
                        ]
                    }
                },
                { label: '<span class="required">*</span>单位', name: 'dw', width: 50, editwidth: '100%', align: 'center', editable: true, hidden:true },
                { label: '<span class="required">*</span>金额', name: 'je', width: 60, editwidth: '100%', align: 'center', editable: true },
                { label: '嘱托', name: 'Remark', width: 153, editwidth: '100%', align: 'center',  editoptions: {
                    dataEvents: [
                                {
                                    type: 'keydown',
                                    fn: function (e) {
                                        if(e.keyCode == 13){
                                            var row = $(e.target).closest('tr.jqgrow');
                                            var rowid = row.attr('id');
                                            var saveResult =$gridzycf.saveRow(rowid, null, null, null, function (callbackRowId) { }, null, null);
                                            if (!saveResult) {
                                                return;
                                            }
                                            addTCMRowData(rowid);   //新增一条明细
                                        }
                                    }
                                }
                    ]
                }, editable: true },
                {
                    label: '转自费', name: 'iszzf', width: 80, editwidth: '100%', align: 'center', edittype: "select", editable: true, editoptions: {
                        dataEvents: [
                            {
                                type: 'change',
                                fn: function (e) {
                                    var row = $(e.target).closest('tr.jqgrow');
                                    var rowid = row.attr('id');
                                    $("#" + rowid + "_zzfbz").val($(this).val());
                                }
                            }
                        ]

                    }
                },
                { label: 'zzfbz', name: 'zzfbz', editwidth: '', align: 'center', editable: true, hidden: true },
                { label: '操作', name: 'action', width: 110, align: 'center' }
            ],
            editinputwidthborder: false,    //是否需要边框 默认为true
            editinputborderradius: false,   //是否需要边框圆角 默认true（有圆角）
            pager: "#gridzycfPager",
            loadComplete: function () {
            },
            gridComplete: function () {
                EnableTCMInlineEditBox();
                //
                if ($("#gridzycf").jqGrid('getRowData_AllLine').length > 0) {
                    //不可再新增新处方
                    $('.glyphicon-new-window:visible').parent('div.ui-pg-div').addClass('newZycfDisableBackgroud');
                }
            }
        });
        //二级菜单
        $gridzycf.jqGrid('setGroupHeaders', {
            useColSpanStyle: true,
            groupHeaders: [
            {
                startColumnName: 'ypCode',
                numberOfColumns: 4,
                titleText: '基本信息'
            }, {
                startColumnName: 'mcjl',
                numberOfColumns: 2,
                titleText: '每次剂量'
            }]
        });
        //自定义按钮
        $gridzycf.navGrid('#gridzycfPager',
                {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false,
                    view: false,
                    position: "left",
                    cloneToTop: false
                })
            .navButtonAdd('#gridzycfPager',
                {
                    buttonicon: "glyphicon glyphicon-remove",
                    title: "删除明细",
                    caption: "删除明细",
                    position: "last",
                    onClickButton: function() {
                        $.each($("#gridzycf").jqGrid('getRowData_AllLine', true, true),
                            function() { //1.删除行
                                var selRowId = $(this.ypmc).attr('rowid');
                                deleteTCMRowData(selRowId, false);
                            });
                        CalculateTCMPresAmount(); //2.计算处方的金额
                    }
                }).navSeparatorAdd("#gridzycfPager", { sepclass: "ui-separator", sepcontent: '' })
            .navButtonAdd('#gridzycfPager',
                {
                    buttonicon: "glyphicon glyphicon-new-window",
                    title: "新处方",
                    caption: "新处方",
                    position: "last",
                    onClickButton: function() {
                        if ($("#gridzycf").jqGrid('getRowData_AllLine').length > 0) {
                            $.modalAlert("不能同时编辑多张中药处方", 'warning');
                            return;
                        }
                        newTCMPresData();
                    }
            });
        $("#gridzycfPager_right").append('<span style="color:red;">特殊处方：</span><select id="tip_jmcf"><option value="">==请选择==</option><option value="LXGB">离休干部</option><option value="TBCF">特病处方</option></select>');
    }
    function EnableTCMInlineEditBox(){
        var ids = $("#gridzycf").getDataIDs();
        $.each(ids, function () {
            //打开编辑模式
            $("#gridzycf").jqGrid('editRow', this, false, initTCMInlineFunc);

            //CalculateTCMEachLineSlANDJe(this, false);
        });

        CalculateTCMPresAmount();
	}

    //初始化 浮层
	function initTCMInlineFunc(rowid) {

		

        //部分列只读
        $("#" + rowid + "_dj").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_ypgg").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_mcjldw").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_je").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_Remark").parent().next().children('select').html('');
        $("#" + rowid + "_Remark").parent().next().children('select').append('<option value="1">是</option><option value="0">否</option>');

        var iszzfval = $("#" + rowid + "_zzfbz").val();
        if (!!iszzfval) {
            $("#" + rowid + "_Remark").parent().next().children('select').val(iszzfval).trigger("change");
        } else {
            $("#" + rowid + "_Remark").parent().next().children('select').val(0).trigger("change");
        }
        

        //根据贴数和剂量算出来的

        //$("#" + rowid + "_sl").css('background-color','#f6f7fb').attr('readonly','true');
        $("#" + rowid + "_ypmc").attr('autocomplete', 'off');

        var currlineCfh = $("#gridzycf").getRowData(rowid).cfh;
        //药品浮层  //中药西药 会重复么 ‘"#" + rowid + "_ypmc"’
        $("#" + rowid + "_ypmc").sfxmFloatingSelector({
            djDecimalPlaces: 4,
            searchType: '@(isMedicineSearchRelatedKC ? "yp.kc" : "yp")', //药品是否显示库存
            ajaxparameters: function ($thisinput) {
                 var flag = false;
                //限制用药的话，flag=true
                if (window.currPatientInfo.brxzCode != "" &&'@ViewBag.ControlbrxzCode'.indexOf(window.currPatientInfo.brxzCode) > -1) {
                    flag = true;
                }
                return "onlyybflag=" + flag + "&mzzybz=1&dllb=1&sfdllx=TCM&keyword=" + $.trim($thisinput.val());
			},
			
			itemdbclickhandler: function ($this) {

				$.ajax({
					url: "/SystemManage/SysBaseData/GetPermissions",
					dataType: "json",
					data: { "tsypzl": $this.attr('data-tsypbz'), "dlcode": $this.attr('data-sfdlCode'), "kssqxjb": $this.attr('data-kssqxjb') },
					type: "POST",
					async: true,
					success: function (req) {
						if (req < '1') {
							if (req == '-1') {
								$.modalAlert("暂无开立" + $this.attr('data-tsypbzmc') + "类药品权限", 'warning');
								$("#" + rowid + "_ypmc").val("");
								$("#" + rowid + "_xmmc").val("");
								$("#" + rowid + "_xmdm").val("");
								$("#" + rowid + "_ypgg").val("");
								$("#" + rowid + "_dj").val("");
								$("#" + rowid + "_redundant_jldw").val("");
								$("#" + rowid + "_dw").val("");
								return;
							}
							if (req == '-2') {
								$.modalAlert("暂无开立" + $this.attr('data-kssmc') + "类药品权限", 'warning');
								$("#" + rowid + "_ypmc").val("");
								$("#" + rowid + "_xmmc").val("");
								$("#" + rowid + "_xmdm").val("");
								$("#" + rowid + "_ypgg").val("");
								$("#" + rowid + "_dj").val("");
								$("#" + rowid + "_redundant_jldw").val("");
								$("#" + rowid + "_dw").val("");
								return;
							}
							if (req == '-3') {
								$.modalAlert("暂无开立" + $this.attr('data-sfdlmc') + "类药品权限", 'warning');
								$("#" + rowid + "_ypmc").val("");
								$("#" + rowid + "_xmmc").val("");
								$("#" + rowid + "_xmdm").val("");
								$("#" + rowid + "_ypgg").val("");
								$("#" + rowid + "_dj").val("");
								$("#" + rowid + "_redundant_jldw").val("");
								$("#" + rowid + "_dw").val("");
								return;
							}

						}
					}
				});

                var xzyysm=$this.attr('data-xzyysm');
                var xzyy= $this.attr('data-xzyy');
                if (xzyy) {
                    $.modalOpen({
                        id: "XzyyForm",
                        title: "限制用药说明",
                        url: "/TemplateManage/PresTemplate/XzyyForm?keyValue=" + xzyysm,
                        width: "400px",
                        height: "200px",
                        callBack: function (iframeId) {
                            var sfkbRadio = top.frames[iframeId].submitForm();
                            if (sfkbRadio!=null&&sfkbRadio!="") {
                                //更改某一行某一列的值
                                $("#gridxycf").jqGrid('setCell',rowid,"xzsybz",sfkbRadio);
                                $.modalClose("XzyyForm");
                            }

                        }
                    });
                }
                //检查重复
                var isRepeatedAdd = false;
                var addypCode = $this.attr('data-sfxmCode');
                $.each($("#gridzycf").getDataIDs(), function () {
                    var cfh = $("#gridzycf").getRowData(String(this)).cfh;
                    var ypCode = $('#' + $($("#gridzycf").getRowData(String(this)).ypCode).attr('id')).val();
                    if (addypCode == ypCode && String(this) != rowid && cfh == currlineCfh) {
                        isRepeatedAdd = true;
                        return;
                    }
                });
                if (isRepeatedAdd) {
                    $.modalAlert("单张处方下明细不能重复", 'warning');
                    return;
                }
                //
                $("#" + rowid + "_zxks").val($this.attr('data-yfbmCode'));
                //
                $("#" + rowid + "_ypmc").val($this.attr('data-sfxmmc'));
                $("#" + rowid + "_ypCode").val($this.attr('data-sfxmCode'));
                $("#" + rowid + "_ypgg").val($this.attr('data-gg'));
                $("#" + rowid + "_dj").val($this.attr('data-dj'));
                $("#" + rowid + "_mcjldw").val($this.attr('data-jldw'));
                $("#" + rowid + "_dw").val($this.attr('data-dw'));
                $("#" + rowid + "_mcjl").val($this.attr('data-mrjl'));

                $("#" + rowid + "_ypmc").css('background-color','#f6f7fb').attr('readonly','true');
                CalculateTCMEachLineSlANDJe(rowid);   //计算明细里的金额和处方金额

                if(isMedicineSearchRelatedKC === 'True'){
                    //库存数量
                    var kcsl = parseInt($this.attr('data-kcsl'));
                    var cls = parseInt($this.attr('data-cls'));
                    var mzkcsl = !!kcsl && !!cls ? (parseInt(kcsl / cls)) : 0;
                    ypkcrem($this.attr('data-yfbmCode'), $this.attr('data-sfxmCode'), mzkcsl);
                }
			}

		

        });
        //嘱托浮层
        $("#" + rowid + "_Remark").ztFloatingSelector({
            height:100,
            itemdbclickhandler: function ($this) {
                $("#" + rowid + "_Remark").val($this.attr('data-ztmc'));
            },
		});

		
    }

    //计算明细里的数量
    function CalculateTCMEachLineSlANDJe(rowid, recalc) {
        var currRowZe = 0.00;

        var tieshu = $.undefinedwith0($('#tieshu').val());    //贴数
        var mcjl = $('#' + rowid + '_mcjl').val();     //剂量

        if(tieshu && mcjl){
            $('#' + rowid + '_sl').val(roundingBy4she6ru5chengshuang((parseFloat(tieshu) * parseFloat($.undefinedwith0(mcjl))),0))

            //下面计算明细里的金额
            var currRowSl = $('#' + rowid + '_sl').val(); //数量
            var currRowDj = $('#' + rowid + '_dj').val();

            //前提：中药的单位、剂量单位要维护的一致
            if (currRowDj && parseFloat(currRowSl) > 0) {
                //单价 数量 不为空
                currRowZe = roundingBy4she6ru5chengshuang(parseFloat(currRowDj) * parseFloat(currRowSl),2);
            }

            $('#' + rowid + '_je').val(currRowZe);
        }
        if(!(recalc === false)){
            //下面计算整个处方的金额
            CalculateTCMPresAmount();
        }
    }

    //计算明细里的金额
    function CalculateTCMEachLineJe(rowid) {
        //下面计算明细里的金额
        var currRowSl = $('#' + rowid + '_sl').val(); //数量
        var currRowDj = $('#' + rowid + '_dj').val();

        //前提：中药的单位、剂量单位要维护的一致
        if (currRowDj && parseFloat(currRowSl) > 0) {
            //单价 数量 不为空
            currRowZe = roundingBy4she6ru5chengshuang(parseFloat(currRowDj) * parseFloat(currRowSl), 2);
        }

        $('#' + rowid + '_je').val(currRowZe);
        CalculateTCMPresAmount();
    }

    //计算处方金额
    function CalculateTCMPresAmount() {
        var allData = $("#gridzycf").jqGrid('getRowData_AllLine');
        if(!!!allData || !!!allData.length || allData.length == 0){
            $('#tdTCMTotalAmount').html('');  //先清空
            $('#tdTCMTotalAmount').append('<label style="color:red;">￥' + 0.00 + '</label>');
            return;
        }
        //allData提前验证 列表中只能一个处方
        var justOneCf = true;
        for (var i = 0; i < allData.length; i++) {
            if(allData[i].cfh != allData[0].cfh){
                justOneCf = false;
            }
        }
        if(!justOneCf){
            alert('处方异常');
            location.href = location.href;
        }
        var totalAmount = 0.00;
        for (var i = 0; i < allData.length; i++) {
            var cfje = $("#" + allData[i].jqRowId + "_je").val();
            if(!!cfje){
                totalAmount += parseFloat(cfje);
            }
        }
        var tieshu = $.undefinedwith0($('#tieshu').val());
        var djbz = $('#djbz').is(':checked');
        if(djbz && !!$('#djbz').attr('data-djfdj')){
            var djf = parseFloat($('#djbz').attr('data-djfdj')) * parseFloat(tieshu);
            var djzfy = parseFloat(totalAmount) + parseFloat(djf);
            totalAmount = roundingBy4she6ru5chengshuang(djzfy,2)  //加上代煎费的算法：代煎单价*贴数
        }
        else{
            totalAmount =totalAmount.toFixed(2);
        }

        $('#tdTCMTotalAmount').html('');  //先清空
        $('#tdTCMTotalAmount').append('<label style="color:red;">￥' + totalAmount + '</label>');
    }

    //是否代煎，关联费用
    $('#djbz').change(function(){
        CalculateTCMPresAmount();
    });

    $('#tieshu').change(function(){
        var val = $(this).val();
        if(val.replace(/(^\s*)|(\s*$)/g, "") == ""){
            $.modalAlert("剂数为空，请确认。", 'warning');
            return;
        }
        if(isNaN(val)){
            $.modalAlert("剂数：请填写数字", 'warning');
            $(this).val('')
            return;
        }
        $.each($("#gridzycf").getDataIDs(), function () {
            CalculateTCMEachLineSlANDJe(String(this));   //此处应该是计算每行的数量和金额（该方法中包含计算处方金额）
        });
    });

    //新处方 按钮
    function newTCMPresData() {
        var dataRow = {
            cfId: null, //尚未保存到数据库
            cfh: GetNewPresNo(),
            ybwym:GetGuid(19,62),
            action: getTCMActionStr()
        };
        $("#gridzycf").jqGrid("addRowData", undefined, dataRow, "last");
        var rowIds = $("#gridzycf").jqGrid('getDataIDs');
        $("#"+rowIds[rowIds.length-1]+"_ypmc").focus();
    }

    //新增明细
    function addTCMRowData(selRowId) {
        var selRowData = $("#gridzycf").getRowData(selRowId);
        //2 新加一行
        var dataRow = {
            cfId: selRowData.cfId,
            cfh: selRowData.cfh,
            ybwym:GetGuid(19,62),
            action: getTCMActionStr()
        };
        $("#gridzycf").jqGrid("addRowData", undefined, dataRow, "after", selRowId);
    }

    //删除明细
    function deleteTCMRowData(selRowId, recalc) {
        if (!!selRowId) {
            delSqtx("zycf",selRowId);
            $("#gridzycf").jqGrid("delRowData", selRowId);
            if(!(recalc === false)){
                CalculateTCMPresAmount();
            }
            if($("#gridzycf").jqGrid('getDataIDs').length == 0){
                $('.glyphicon-new-window:visible').parent('div.ui-pg-div').removeClass('newZycfDisableBackgroud');
            }
        }
    }

    //保存
    function SaveTCMPres(savetodb, justUpdateAlldataArray) {
        //必填信息验证  （主诉、发病时间）
        if (!$('#formTCM').formValid(valOptions)) {
            $.modalAlert("必填信息尚未完善", 'warning');
            return;
        }
        //获取所有行Id，遍历使编辑框处于保存状态
        var rowIds = $("#gridzycf").jqGrid('getDataIDs');
        for (var i = 0; i < rowIds.length; i++) {
            var saveResult = $("#gridzycf").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);
            //库存检验
            if(isMedicineSearchRelatedKC === 'True'){
                var rowData = $("#gridzycf").getRowData(rowIds[i]);
                var thissl = rowData.sl;
                if(thissl){
                    if(!ypkccheck(rowData.zxks,rowData.ypCode,parseInt(thissl))){
                        $.modalAlert(rowData.ypmc + "药品库存不足", "error");
                        saveResult = false;
                    }
                }
            }
            if (!saveResult) {
                EnableTCMInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                return;   //保存失败，则return
            }
        }
        var tieshu = $('#tieshu').val();
        var cfyf = $('#cfyf').val();
        var djbz = $('#djbz').is(':checked');
        var gridzycfData = $("#gridzycf").jqGrid('getRowData_AllLine', null, true);
        $.each(gridzycfData, function () {    //去掉action
            delete this.action;   //去掉action
            delete this.jqRowId;   //去掉jqRowId

            if (savetodb == '1') {
                if (this.ypmc == undefined || this.ypmc == "") {
                    $.modalAlert("缺少名称", "warning");
                    saveResult = false;
                    return false;
                } else if (this.ypgg == undefined || this.ypgg == "") {
                    $.modalAlert("缺少规格", "warning");
                    saveResult = false;
                    return false;
                } else if (isNaN(this.dj) || this.dj == "") {
                    $.modalAlert("缺少单价", "warning");
                    saveResult = false;
                    return false;
                } else if (isNaN(this.mcjl) || this.mcjl == "") {
                    $.modalAlert("缺少剂量", "warning");
                    saveResult = false;
                    return false;
                } else if (this.mcjldw === undefined || this.mcjldw == "") {
                    $.modalAlert("缺少单位", "warning");
                    saveResult = false;
                    return false;
                } else if (isNaN(this.sl) || this.sl == "") {
                    $.modalAlert("缺少数量", "warning");
                    saveResult = false;
                    return false;
                } else if (this.dw === undefined || this.dw == "") {
                    $.modalAlert("缺少单位", "warning");
                    saveResult = false;
                    return false;
                } else if (isNaN(this.je) || this.je == "") {
                    $.modalAlert("缺少金额", "warning");
                    saveResult = false;
                    return false;
                }
            }


            this.tieshu = tieshu;
            this.cfyf = cfyf;
            this.djbz = djbz;
            this.sfbz = false;
            var thismxCfId = this.cfId;
            var matchedHisCf = $.jsonWhere(window.alldataArray.zycf, function(icfmx){
                return !!icfmx.cfId && icfmx.cfId == thismxCfId;
            });
            if(matchedHisCf && matchedHisCf.length){
                this.cfzhdysj = matchedHisCf[0].cfzhdysj;
                this.sendtohisResult = matchedHisCf[0].sendtohisResult;
                this.klrq = matchedHisCf[0].klrq;
            }
            this.cftag = $("#tip_jmcf").val();
        });

        if (!saveResult) {
            EnableTCMInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
            return;   //保存失败，则return
        }
        //保存数据
        window.alldataArray.zycf = $.jsonWhere(window.alldataArray.zycf, function(icfmx){
            if(!!!icfmx.cfId){
                return false;   //编辑列表里有
            }
            for(var iIndex = 0; iIndex < gridzycfData.length; iIndex++){
                if(gridzycfData[iIndex].cfh == icfmx.cfh){
                    return false;
                }
            }
            return true;
        });
        $.each(gridzycfData, function(){
            window.alldataArray.zycf.push(this);
        });


        zylocaldata = new Array();

        if(!(justUpdateAlldataArray == true)){
            if(savetodb == '1'){
                if (SaveData(false, function(){
                    window.initHistoryPresTree('@Html.Raw(((int)EnumCflx.TCMPres).ToString())');

                    $.modalAlert("保存成功", 'success');
                })) {
                    $("#gridzycf").clearGridData();
                } else {
                    EnableTCMInlineEditBox();
                }
            }
            else{
                //跳回病历页
                $('#myTab [href="#linkbl"]').trigger('click'); //初始化显示哪个tab
                //病例页重新加载处方，处方数据发生了变更
                triggleActive();
            }
        }
        else {
            triggleActive();
        }
    }

    function getTCMActionStr() {
        return "<i class='fa fa-plus-square-o' style='font-size: large; color: #09a3ea;' onclick='addTCMRowData($(this).parent().parent().attr(\"id\"));return false;'></i>&nbsp;&nbsp;&nbsp;<i class='fa fa-minus-square-o' style='font-size: large; color: #09a3ea;' onclick='deleteTCMRowData($(this).parent().parent().attr(\"id\"));return false;'></i>";
    }

    //另存为模板
    function saveAsTCMTemplate(){
        $.modalOpen({
            id: "Form",
            title: "存为模板",
            url: "/MedicalRecord/Form",
            width: "400px",
            height: "250px",
            callBack: function (iframeId) {
                var mbObj = top.frames[iframeId].submitForm();
                if (!(mbObj && mbObj.mbmc && mbObj.mblx)) {
                    return;
                }
                $.modalClose("Form");
                //模板表
                var mbObj = {
                    mblx: mbObj.mblx,
                    cflx: @Html.Raw(((int)EnumCflx.TCMPres).ToString()),
                    mbmc: mbObj.mbmc,
                }
                //获取所有行Id，遍历使编辑框处于保存状态
                var rowIds = $("#gridzycf").jqGrid('getDataIDs');
                for (var i = 0; i < rowIds.length; i++) {
                    var saveResult = $("#gridzycf").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);

                    if (!saveResult) {
                        EnableTCMInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                        return;   //保存失败，则return
                    }
                }
                var gridzycfData = $("#gridzycf").jqGrid('getRowData_AllLine');
                if(!gridzycfData || gridzycfData.length==0){
                    $.modalAlert("模板明细不能为空", 'warning');
                    return;
                }

                mbObj.tieshu = $('#tieshu').val();
                mbObj.cfyf = $('#cfyf').val();
                mbObj.djbz = $('#djbz').is(':checked');

                $.each(gridzycfData, function () {    //去掉action
                    delete this.action;   //去掉action
                    delete this.jqRowId;   //去掉jqRowId
                });

                $.najax({
                    url: "/TemplateManage/PresTemplate/SaveData",
                    dataType: "json",
                    data: { mbObj: mbObj, mxList: gridzycfData },
                    type: "POST",
                    success: function (data) {
                        $.modalAlert("保存成功", 'warning');
                        window.$('#current').trigger('click');
                    },
                    complete:function(){
                        EnableWMInlineEditBox();    //重启启用编辑 否则下次Save时会返回false
                    }
                });

            }
        });
    }

</script>
